package com.enjoy.rocketmq.simple;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * 简单样例：异步发送消息
 */
public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException {
        // 在ClientLogger中定义了一些常量来配置系统的环境变量，启用slf4j，默认启用inner
        System.setProperty(ClientLogger.CLIENT_LOG_USESLF4J, "true");

        DefaultMQProducer producer = new DefaultMQProducer("Jodie_Daily_test");
        producer.setNamesrvAddr("127.0.0.1:9876");
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(3);

        CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < 5; i++) {
            int index = i;
            Message msg = new Message("TopicTest", "TagA", "OrderID188", "hello,world".getBytes(RemotingHelper.DEFAULT_CHARSET));
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("%-10d ok %s %n", index, sendResult.getMsgId());
                    latch.countDown();
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println("e = " + e);
                    latch.countDown();
                }
            });

        }
        latch.await();
        producer.shutdown();


    }
}
